import 'dart:async';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ConfigHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/Constant.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/SpHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ViewHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/login/LoginVM.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/login/RegisteredWidget.dart';

typedef IndexCallback =Function (int);
typedef FutureCallback =Future<bool> Function ();

LoginVM loginVM=LoginVM();
//登录
class LoginWidget extends StatefulWidget {

  const LoginWidget({Key? key}) : super(key: key);

  @override
  _LoginWidgetState createState() => _LoginWidgetState();
}

class _LoginWidgetState extends State<LoginWidget> {

  int type=1;//登录方式  1.密码登录 2 快捷登录
  bool isInputMeet=false;
  bool isSelected=false;
  TextEditingController _phoneController=TextEditingController();
  TextEditingController _pwController=TextEditingController();
  TextEditingController _codeController=TextEditingController();
  late IndexCallback  callback;  //登录方式 回调

  @override
  void initState() {
    super.initState();
    callback=(index){
      setState(() {
        type=index;
      });
    };
  }
  @override
  void dispose() {
    super.dispose();
    _phoneController.dispose();
    _pwController.dispose();
    _codeController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget editWidget;
    if(type==1){
      editWidget= PWEditWidget(_phoneController,_pwController,(str){
        String phone = _phoneController.text;
        String pw = _pwController.text;
        isInputMeet=phone.length>6 && pw.length>4;
        setState(() {});
      });
    }else{
      editWidget= QuickEditWidget(_phoneController, _codeController, (value) {
        String phone = _phoneController.text;
        String code = _codeController.text;
        isInputMeet=phone.length>6 && code.length>=4;
        setState(() {});
      }, () { // 输入验证码
        var phone = _phoneController.text;
        if(phone.isNotEmpty){
          loginVM.onSMSVerCode(phone: phone,type: 2);
          return Future.value(true);
        }else{
          showCenterToast("请输入手机号");
        }
        return Future.value(false);
      });
    }
    if(SPHelper.getPhone()!=null && SPHelper.getPhone()!.isNotEmpty){
      _phoneController.text=SPHelper.getPhone()??"";
    }

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //标题栏
              Container(
                margin: EdgeInsets.fromLTRB(0, 20.h, 0, 0),
                  child: DufTitleBar()),
              Padding(padding: EdgeInsets.fromLTRB(0, 40.h, 0, 0)),
              //登录方式按钮
              LoginTypeWitget(type,callback),
              //输入框
              editWidget,
              //登录按钮
              Container(
                width: double.infinity,
                margin: EdgeInsets.fromLTRB(30.w, 30.h, 30.w, 0),
                child: ElevatedButton(
                  onPressed: (){
                      if(!isInputMeet){
                        showCenterToast("请输入正确的账号密码");
                        return;
                      }
                      onLogin();
                  },
                  child: Text("登录",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
                  style: ButtonStyle(
                      backgroundColor:MaterialStateProperty.all(Color(isInputMeet?ConstantColors.mainColor:0XFFdddddd)),
                      fixedSize:MaterialStateProperty.all(Size(double.infinity, 44.h)),
                      shape:MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(22.h)))
                  ),
                ),
              ),
              //注册和 忘记密码
              Container(
                margin: EdgeInsets.fromLTRB(30.w, 15.h, 30.w, 15.h),
                child: Row(
                  children: [
                     Expanded(child: TextButton(onPressed: () { Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
                         return RegisteredWidget();
                       }));
                     },style: ButtonStyle(alignment: Alignment.centerLeft),
                       child: Text("注册",style: TextStyle(fontSize: 14.sp,color: Color(0xff999999)),textAlign: TextAlign.left,))),
                     Expanded(child: TextButton(onPressed: () {  },style: ButtonStyle(alignment: Alignment.centerRight),
                       child: Text("忘记密码？",style: TextStyle(fontSize: 14.sp,color: Color(0xff999999)),textAlign: TextAlign.right,))),
                  ],
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.bottomCenter,
                  padding: EdgeInsets.fromLTRB(24.w, 0, 24.w, 16.h),
                  child: Row(
                     children: [
                        Container(
                           height: 40.h,
                           padding: EdgeInsets.fromLTRB(0, 0, 8.sp, 0),
                           alignment: Alignment.topCenter,
                           child: DufCheckbox(value: isSelected, radius: 7.sp,onChanged: (value){
                             isSelected=value==true?true:false;
                             setState(() {});
                           },),
                        ),
                        Container(
                           height: 40.h,
                           alignment: Alignment.topLeft,
                           width: MediaQuery.of(context).size.width-106.w,
                           child: Text.rich(
                              TextSpan(
                                 text: "未注册的手机号验证后将自动创建源选帐号，我已阅读并 同意：",style: TextStyle(fontSize: 12.sp,color: Colors.black),
                                 children: [
                                  // WidgetSpan(child: Text("未注册的手机号验证后将自动创建源选帐号，我已阅读并 同意：",style: TextStyle(fontSize: 12.sp,color: Colors.black),)),
                                  WidgetSpan(child: InkWell(onTap: (){}, child: Text("《用户协议》",style: TextStyle(fontSize: 12.sp,color: Color(0xff0267FF)),))),
                                  WidgetSpan(child: InkWell(onTap: (){}, child: Text("《隐私声明》",style: TextStyle(fontSize: 12.sp,color: Color(0xff0267FF)),))),
                                ]),
                              softWrap: true,
                           ),
                       )
                     ],
                   ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  //登录
  void onLogin() {
    FocusManager.instance.primaryFocus?.unfocus();
    var phone = _phoneController.text;
    if(!isSelected){
      showCenterToast("您尚未同意登录相关条款！");
      return ;
    }
    if(phone.isEmpty){
      showCenterToast("请输入手机号");
      return;
    }
    var done=(){
       var loginBean = loginVM.loginBean;
       if(loginBean!=null){
          SPHelper.saveLoginInfo(loginBean);
          Navigator.of(context).pop();
       }
    };
    if(type==1){
      var pw = _pwController.text;
      if(pw.isEmpty){
        showCenterToast("请输入密码");
        return;
      }
      loginVM.getAppLogin(phone: phone, password: pw,requestDone: done);
    }else{
      var code = _codeController.text;
      if(code.isEmpty){
        showCenterToast("请输入验证码");
        return;
      }
      loginVM.getLoginQuick(phone: phone, code: code,requestDone: done);
    }
  }
}

//登录方式按钮
class LoginTypeWitget extends StatefulWidget {

  int type=-1;//登录方式  1.密码登录 2 快捷登录

  IndexCallback _indexCallback;

  LoginTypeWitget(this.type,this._indexCallback);

  @override
  _LoginTypeWitgetState createState() => _LoginTypeWitgetState();
}

class _LoginTypeWitgetState extends State<LoginTypeWitget> {

  @override
  Widget build(BuildContext context) {
    return Row(children: [
      Container(
        width: 94.sp,
        margin: EdgeInsets.fromLTRB(30.w, 0, 0, 0),
        alignment: Alignment.center,
        child: TextButton(
          style: ButtonStyle(overlayColor: MaterialStateProperty.all(Colors.transparent)),
          onPressed: (){
            widget.type=1;
            setState(() {
               widget._indexCallback(widget.type);
             });
          },
          child: Stack(
            alignment: Alignment.center,
            children: [
              Visibility(
                visible: widget.type==1,
                child: Container(
                    width: double.infinity,
                    height: 16.h,
                    margin: EdgeInsets.fromLTRB(0, 18.h, 0, 0),
                    decoration: ShapeDecoration(
                        gradient: LinearGradient(begin: Alignment.bottomRight,end:Alignment.topLeft,colors: [Color(0xffFF905F),Color(0xffFFC194)]),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(Radius.circular(8.sp))
                        )
                    )
                ),
              ),
              Text("密码登录",style: TextStyle(fontSize: 18.sp,color: Color(0xff333333)),textAlign: TextAlign.center,),
            ],
          ),
        ),
      ),
      Container(
        width: 94.sp,
        margin: EdgeInsets.fromLTRB(35.w, 0, 0, 0),
        alignment: Alignment.center,
        child: TextButton(
          style: ButtonStyle(overlayColor: MaterialStateProperty.all(Colors.transparent)),
          onPressed: (){
            widget.type=2;
            setState(() {
              widget._indexCallback(widget.type);
            });
          },
          child: Stack(
            alignment: Alignment.center,
            children: [
              Visibility(
                visible: widget.type==2,
                child: Container(
                    width: double.infinity,
                    height: 16.h,
                    margin: EdgeInsets.fromLTRB(0, 18.h, 0, 0),
                    decoration: ShapeDecoration(
                        gradient: LinearGradient(begin: Alignment.bottomRight,end:Alignment.topLeft,colors: [Color(0xffFF905F),Color(0xffFFC194)]),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(Radius.circular(8.sp))
                        )
                    )
                ),
              ),
              Text("快捷登录",style: TextStyle(fontSize: 18.sp,color: Color(0xff333333)),textAlign: TextAlign.center,),
            ],
          ),
        ),
      ),
    ],);
  }
}

class PWEditWidget extends StatefulWidget {

  TextEditingController _phoneController;
  TextEditingController _pwController;
  ValueChanged<String>? onChanged;
  ValueChanged<String>? onSubmitted;

  bool lookPW=false;

  PWEditWidget(this._phoneController, this._pwController,this.onChanged,{this.onSubmitted});

  @override
  _PWEditWidgetState createState() => _PWEditWidgetState();
}

class _PWEditWidgetState extends State<PWEditWidget> {

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(40.w, 40.h, 40.w, 0),
      color: Colors.white,
      child: Column(
        children: [
          Container(
              height: 80.h,
              child: TextField(
                onChanged: widget.onChanged,
                controller: widget._phoneController,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.next,
                maxLength: 11,
                decoration: InputDecoration(
                  hintText: "请输入账号",
                  counterText: '',
                  suffixIcon:widget._phoneController.text.isEmpty?null:IconButton(
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onPressed: (){
                        widget._phoneController.clear();
                      }, icon: Image.asset(assetPath("ic_close_gray_small.png"),height:12.h ,fit: BoxFit.fitHeight,)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  prefixIcon: Container(
                      width: 90.w,
                      child: Row(
                        children: [
                          Text("中国(+86) ",style: TextStyle(color: Color(0xff333333),fontSize: 14.sp),),
                          Padding(
                            padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 0),
                            child: Image.asset(assetPath("ic_find_extend1.png"),height: 5.h,fit:BoxFit.fitHeight,),
                          ),
                        ],
                      )),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
          Container(
              height: 80.h,
              child: TextField(
                onChanged: widget.onChanged,
                controller: widget._pwController,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.send,
                onSubmitted: widget.onSubmitted,
                obscuringCharacter: "*",
                obscureText: !widget.lookPW,
                maxLength: 24,
                decoration: InputDecoration(
                  counterText: '',
                  hintText: "请输入密码",
                  suffixIcon:IconButton(
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onPressed: (){
                        setState(() {
                           widget.lookPW=!widget.lookPW;
                        });
                      }, icon: Image.asset(assetPath(widget.lookPW?"ic_eye_visible.png":"ic_eye_def.png"),height:14.h ,fit: BoxFit.fitHeight,)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
        ],
      ),
    );
  }
}


//快捷登录
class QuickEditWidget extends StatefulWidget {

  TextEditingController _phoneController; //电话文本框 监听器
  TextEditingController _codeController;//验证码文本框 监听器
  ValueChanged<String>? _onChanged;//文本框 输入触发器
  FutureCallback futureCallback;
  int currentTiming=ConfigHelper.verificationCodeTiming;

  QuickEditWidget(this._phoneController, this._codeController,this._onChanged,this.futureCallback);

  @override
  _QuickWidgetState createState() => _QuickWidgetState();
}

class _QuickWidgetState extends State<QuickEditWidget> {

  Timer? timer;

  @override
  void initState() {
    super.initState();
  }

  //重新计时
  void newTimer(){
    timer?.cancel();
    widget.currentTiming=ConfigHelper.verificationCodeTiming;
    timer = Timer.periodic(Duration(seconds: 1), (index) {
      widget.currentTiming--;
      if(widget.currentTiming<=0){
        timer?.cancel();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(40.w, 40.h, 40.w, 0),
      color: Colors.white,
      child: Column(
        children: [
          Container(
              height: 80.h,
              child: TextField(
                onChanged: widget._onChanged,
                controller: widget._phoneController,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.next,
                maxLength: 24,
                decoration: InputDecoration(
                  counterText: "",
                  hintText: "请输入账号",
                  suffixIcon:widget._phoneController.text.isEmpty?null:IconButton(
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onPressed: (){
                        widget._phoneController.clear();
                      }, icon: Image.asset(assetPath("ic_close_gray_small.png"),height:12.h ,fit: BoxFit.fitHeight,)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  prefixIcon: Container(
                      width: 90.w,
                      child: Row(
                        children: [
                          Text("中国(+86) ",style: TextStyle(color: Color(0xff333333),fontSize: 14.sp),),
                          Padding(
                            padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 0),
                            child: Image.asset(assetPath("ic_find_extend1.png"),height: 5.h,fit:BoxFit.fitHeight,),
                          ),
                        ],
                      )),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
          Container(
              height: 80.h,
              child: TextField(
                onChanged: widget._onChanged,
                controller: widget._codeController,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.send,
                maxLength: 10,
                decoration: InputDecoration(
                  counterText: '',
                  hintText: "请输入验证码",
                  suffixIcon:TextButton(
                      style: ButtonStyle(overlayColor:MaterialStateProperty.all(timer?.isActive!=true?Colors.black12:Colors.transparent)),
                      onPressed: (){
                        if(timer?.isActive!=true){
                          var future = widget.futureCallback();
                          future.asStream().listen((event) {
                              if(event){
                                newTimer();
                              }
                          });
                        }
                      },
                      child: Text(timer?.isActive==true?"重新发送(${widget.currentTiming})":"获取验证码",style: TextStyle(fontSize: 12.sp,color: Color(timer?.isActive==true?0xff999999:0xfffF862D)),)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
        ],
      ),
    );
  }
}